//
//  DSFScanQRCodeViewController.m
//  TVFan3.0
//
//  Created by 李赛 on 15-4-13.
//  Copyright (c) 2015年 李胜男. All rights reserved.
//

#import "DSFScanQRCodeViewController.h"
#import "InfomationEditViewController.h"
@interface DSFScanQRCodeViewController ()
@property (nonatomic, assign) BOOL hasPushViewController;
@end

@implementation DSFScanQRCodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title=@"二维码扫描";
    
    _line = [[UIImageView alloc] initWithFrame:CGRectMake((DSF_SCREENWIDTH-200)/2, 100, 200, 2)];
    _line.image = [UIImage imageNamed:@"line.png"];
    [self.view addSubview:_line];
    
    UIImageView *scanBorderImage=[[UIImageView alloc]initWithFrame:CGRectMake((DSF_SCREENWIDTH-200)/2,100,200,200)];
    scanBorderImage.image=[UIImage imageNamed:@"扫描框"];
    [self.view insertSubview:scanBorderImage atIndex:1];
    
    [self createBoderViewWithInterestRect:CGRectMake((DSF_SCREENWIDTH-200)/2,100,200,200) backgroundColor:[UIColor blackColor] alpha:0.6 andFatherView:self.view inserTag:0];
    // Do any additional setup after loading the view, typically from a nib.
}

-(void)createBoderViewWithInterestRect:(CGRect)InterestFrame backgroundColor:(UIColor *)backgroundColor alpha:(CGFloat)alpha andFatherView:(UIView *)fatherView inserTag:(NSInteger)insertTag
{
    UIView *topView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, DSF_SCREENWIDTH, InterestFrame.origin.y)];
    topView.backgroundColor=backgroundColor;
    topView.alpha=alpha;
    [fatherView insertSubview:topView atIndex:insertTag];
    
    UIView *bottomView=[[UIView alloc]initWithFrame:CGRectMake(0, InterestFrame.origin.y+InterestFrame.size.height, DSF_SCREENWIDTH, DSF_SCREENHEIGHT-InterestFrame.origin.y-InterestFrame.size.height)];
    bottomView.backgroundColor=backgroundColor;
    bottomView.alpha=alpha;
    [fatherView insertSubview:bottomView atIndex:insertTag];
    
    UIView *leftView=[[UIView alloc] initWithFrame:CGRectMake(0, InterestFrame.origin.y, InterestFrame.origin.x, InterestFrame.size.height)];
    leftView.backgroundColor=backgroundColor;
    leftView.alpha=alpha;
    [fatherView insertSubview:leftView atIndex:insertTag];
    
    UIView *rightView=[[UIView alloc] initWithFrame:CGRectMake(DSF_SCREENWIDTH-InterestFrame.origin.x, InterestFrame.origin.y, InterestFrame.origin.x, InterestFrame.size.height)];
    rightView.backgroundColor=backgroundColor;
    rightView.alpha=alpha;
    [fatherView insertSubview:rightView atIndex:insertTag];
    
    UILabel *titleLB=[[UILabel alloc]initWithFrame:CGRectMake(InterestFrame.origin.x, InterestFrame.origin.y+InterestFrame.size.height,InterestFrame.size.width , 60)];
    titleLB.text=@"将二维码放入框内，即可自动扫描";
    titleLB.textColor=[UIColor whiteColor];
    titleLB.textAlignment=NSTextAlignmentCenter;
    titleLB.font=[UIFont systemFontOfSize:13];
    [fatherView addSubview:titleLB];
    
//    UILabel *remindLB=[[UILabel alloc]initWithFrame:CGRectMake(10, DSF_SCREENHEIGHT-60,DSF_SCREENWIDTH -20, 60)];
//    remindLB.text=@"将影片地址在 http://sao.tvfan.cn/中生成二维码后扫描";
//    remindLB.numberOfLines=2;
//    remindLB.textColor=[UIColor whiteColor];
//    remindLB.textAlignment=NSTextAlignmentLeft;
//    remindLB.font=[UIFont systemFontOfSize:13];
//    [fatherView addSubview:remindLB];
    
    UIButton *backButton=[[UIButton alloc]initWithFrame:CGRectMake((DSF_SCREENWIDTH-60)/2, DSF_SCREENHEIGHT-120, 60, 40)];
    [backButton addTarget:self action:@selector(backAndDissmissViewController) forControlEvents:UIControlEventTouchUpInside];
    backButton.layer.masksToBounds=YES;
    backButton.layer.cornerRadius=6;
    backButton.layer.borderColor=[[UIColor whiteColor]CGColor];
    backButton.layer.borderWidth=1.0;
    [backButton setTitle:@"返回" forState:UIControlStateNormal];
    [fatherView addSubview:backButton];
}
-(void)backAndDissmissViewController
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"导航-返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(leftButtonContact:)];
    [leftItem setImageInsets:UIEdgeInsetsMake(0, -20, 0, 0)];
    leftItem.tag = 3838;
    [self.navigationItem setLeftBarButtonItem:leftItem];
    [self setupCamera];
    [self addAnimations];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}
-(void)leftButtonContact:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - 动画效果
- (void)addAnimations
{
    CABasicAnimation *translation = [CABasicAnimation animationWithKeyPath:@"position"];

    translation.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    translation.fromValue = [NSValue valueWithCGPoint:CGPointMake(_line.center.x, _line.center.y)];
    translation.toValue = [NSValue valueWithCGPoint:CGPointMake(_line.center.x, _line.center.y+200)];
    translation.duration = 2;
    translation.repeatCount = 99999;
    translation.autoreverses = YES;
    [_line.layer addAnimation:translation forKey:@"translation"];
}


- (void)setupCamera
{
    // Device
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    // Input
    _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
    
    // Output
    _output = [[AVCaptureMetadataOutput alloc]init];
    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    // Session
    _session = [[AVCaptureSession alloc]init];
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    if ([_session canAddInput:self.input])
    {
        [_session addInput:self.input];
    }
    
    if ([_session canAddOutput:self.output])
    {
        [_session addOutput:self.output];
    }
//    _session.sessionPreset=AVCaptureSessionPreset1920x1080;
    // 条码类型 AVMetadataObjectTypeQRCode
    _output.metadataObjectTypes =@[AVMetadataObjectTypeQRCode];

    
    //设置扫描区域的大小
    [ _output setRectOfInterest : CGRectMake ((100)/DSF_SCREENHEIGHT ,100/DSF_SCREENWIDTH,200/DSF_SCREENHEIGHT ,200/DSF_SCREENWIDTH)];

    // Preview
    _preview =[AVCaptureVideoPreviewLayer layerWithSession:self.session];
    _preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    
    // _preview.frame =CGRectMake((DSF_SCREENWIDTH-200)/2,110,200,200);
    _preview.frame =CGRectMake(0,0,DSF_SCREENWIDTH,DSF_SCREENHEIGHT);
    [self.view.layer insertSublayer:self.preview atIndex:0];
    
    
    
    // Start
    [_session startRunning];
}
#pragma mark AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
  

    NSString *stringValue;
    
    if ([metadataObjects count] >0)
    {
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
        stringValue = metadataObject.stringValue;
        
        if (_hasPushViewController==NO) {
             _hasPushViewController=YES;
            UIStoryboard * storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
            InfomationEditViewController *vc = [storyboard  instantiateViewControllerWithIdentifier:@"InfomationEditViewController"];
            [self.navigationController pushViewController:vc animated:YES];
           
        }
   
    }
    //解析
    
//    NSDictionary * responseDict = [stringValue objectFromJSONString];
//
//    NSString *tag=[responseDict objectForKey:@"tag"];
//    NSString *imei = [SvUDIDTools UDID];
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"ScanQRCodeDic" object:nil userInfo:responseDict];
//    [_session stopRunning];
//    [self.navigationController popViewControllerAnimated:YES];
//    [DSFProgram getSaoSuccessWithBlock:^(BOOL result, NSString *failedMessage, NSError *error) {
//        if (result) {
//
//        }
//    } withUserId:[DSFUserInfo shareUserInstance].userRegisterModel.userId andTag:tag andPhoneIdentify:imei];

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
